﻿using Itech_Run.Application.Contracts.Shared.Dto;
using Itech_Run.Application.Shared;
using Itech_Run.Blog.Application.Contracts.Dto;
using Itech_Run.Blog.Application.Contracts.Service;
using Itech_Run.Blog.Domain.Entity;
using Volo.Abp.Domain.Repositories;

namespace Itech_Run.Blog.Application.Service
{
    public class BlogPersonCategoryService : BaseApplicationService<Blog_PersonCategory>, IBlogPersonCategoryService
    {
        private readonly IRepository<Blog_PersonCategory, string> _blogPersonCategoryRepository;
        private readonly IRepository<Blog_PersonCategory_Map, string> _blogPersonCategoryMapRepository;
        public BlogPersonCategoryService(IRepository<Blog_PersonCategory, string> blogPersonCategoryRepository, IRepository<Blog_PersonCategory_Map, string> blogPersonCategoryMapRepository)
        {
            _blogPersonCategoryRepository = blogPersonCategoryRepository;
            _blogPersonCategoryMapRepository = blogPersonCategoryMapRepository;
        }
        public async Task<List<KeyValueDto>> GetListAsync(string operateUser)
        {
            var query =
                from r in await _blogPersonCategoryRepository.GetQueryableAsync()
                where r.IsVisible == true && r.UserId == operateUser
                orderby r.Name ascending
                select new KeyValueDto
                {
                    Key = r.Id,
                    Value = r.Name
                };

            return query.ToList();
        }

        public async Task<List<BlogPersonCategoryHotDto>> GetHotListAsync(string operateUser)
        {
            var query =
                from c in await _blogPersonCategoryRepository.GetQueryableAsync()
                join lm in (await _blogPersonCategoryMapRepository.GetQueryableAsync()).Where(p=>p.Blog.IsPublish==true) on c.Id equals lm.PersonCategoryId
                //into lr
                //from lr1 in lr.DefaultIfEmpty()
                where c.IsVisible == true && c.UserId == operateUser
                group c by new { c.Id, c.Name } into g
                select new BlogPersonCategoryHotDto
                {
                    Id = g.Key.Id,
                    Name = g.Key.Name,
                    Count = g.Count()
                };
            var items = query.ToList();
            return items;
        }
    }
}
